<?php

/**
 * @Author: lujizhang
 * @Date:   2019-10-16 09:26:11
 * @Last Modified by:   lujizhang
 * @Last Modified time: 2019-11-01 20:19:35
 */

namespace app\api\model;
use think\Db;

use app\api\model\Wechat;

class WechatOauth extends Wechat{

    public $oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=";
    public $oauthParams = "&response_type=code&scope=snsapi_userinfo"; //snsapi_base 不弹出授权页
    public $wxSnsApiBase = "https://api.weixin.qq.com/sns";
    
    function __construct($wxAppId){
        parent::__construct($wxAppId);
        $this->oauthUrl .=$wxAppId;
    }

    /**
     * 生成授权认证url返回给前端
     * @param int $state
     * @return mixed
     */
    public function makeOauthUrl($state=8,$toUrl=""){
        
        $call_back_url=$this->callBackUrl;

        if(!empty($toUrl)) {
            $state=1;
            if(strpos($call_back_url,"?")!==false) $call_back_url.="&tourl=".urlencode($toUrl);
            else $call_back_url.="?tourl=".urlencode($toUrl);
        }
        $call_back_url = urlencode($call_back_url);
        
        $url = $this->__makeOauthUrl($call_back_url,$state);
        return $url;
    }

    private function __makeOauthUrl($redirect_uri,$state=1){
        
        /*
         https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID
            &redirect_uri=REDIRECT_URI
            &response_type=code&scope=SCOPE
            &state=STATE
            &component_appid=component_appid#wechat_redirect
         */
        // $redirect_uri=urlencode($redirect_uri);
        $url = $this->oauthUrl.
            "&redirect_uri=".$redirect_uri.
            $this->oauthParams.
            "&state=".$state.
            "&component_appid=".$this->component_appid.
            "#wechat_redirect";
            // var_dump($url);die();
        return $url;
    }


    /**
     * 授权认证处理
     * 通过 code 换取 access_token
     */
    public function oauth($code){
        $appId = $this->wx_app_id;
        $response=$this->getOauthTokenByThird($appId,$code);
        $oauth_info = json_decode($response,true);
        //$union_id=$oauth_info['unionid'];
        if(isset($oauth_info['openid'])){
            $open_id=$oauth_info['openid'];
            $oauth_token=$oauth_info['access_token'];
            //$user_str=json_encode(array("wxUnionId"=>$union_id));

            $response = $this->__getOauthUserInfo($oauth_token,$open_id);
            $arr=json_decode($response);
            $response=json_encode($arr);
            subLog($response,'oauth user');
        }
        

        // $wx_user['openid']=$arr->openid;
        // $wx_user['user_id']=$_SESSION['bybe_uid'];
        // $_COOKIE['wx_user']=json_encode($wx_user);
        // setcookie("wx_user",json_encode($wx_user),time()+365*24*3600,'/');

        //setcookie("webapp_user",$user_str,0,'/',DOMAIN_NAME);
        return $response;
    }

    /**
     * @return mixed
     * {
        "access_token":"ACCESS_TOKEN",
        "expires_in":7200,
        "refresh_token":"REFRESH_TOKEN",
        "openid":"OPENID",
        "scope":"SCOPE",
        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
        }
     */
    protected function __getOauthToken($code){

        $api_url = $this->wxSnsApiBase."/oauth2/access_token".
            "?appid=".$this->wx_app_id."&secret=".$this->wx_app_secret.
            "&code=".$code."&grant_type=authorization_code";
        $weixin_return = $this->httpRequest($api_url);
        subLog($weixin_return,'oauth token'.$api_url);
        return $weixin_return;
    }

    /**
     * oauth后获取用户信息
     * @param $oauth_token
     * @param $open_id
     * @return mixed
     * {
        "openid":" OPENID",
        " nickname": NICKNAME,
        "sex":"1",
        "province":"PROVINCE"
        "city":"CITY",
        "country":"COUNTRY",
        "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
        "privilege":[
        "PRIVILEGE1"
        "PRIVILEGE2"
        ],
        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
    }
     */
    protected  function __getOauthUserInfo($oauth_token,$open_id){
        $api_url = $this->wxSnsApiBase."/userinfo".
            "?access_token=".$oauth_token.
            "&openid=".$open_id."&lang=zh_CN";
        $weixin_return = $this->httpRequest($api_url);
        return $weixin_return;
    }
}